package com.itheima.filter;

import com.itheima.Utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;

import java.io.IOException;

/**
 * 校验Token的过滤器Filter
 * @author GY
 * @version V1.0
 * @date 2025-01-16 16:18
 */
@Slf4j
//@WebFilter("/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        log.info("TokenFilter doFilter running");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        // 1.获取请求路径
        String uri = request.getRequestURI();
//        log.info("uri:{}",uri);
        // 2.判断请求路径是否为登录
        // 2.1登录，放行
        if (uri.contains("/login")){
            chain.doFilter(request,response);
            return;
        }
        // 2.2不是登录，则校验token
        // 3.从请求头中获取token
        String token = request.getHeader("token");
//        log.info("token:{}",token);
        // 3.1判断token是否为空，如果为空，则返回401，拦截请求
        if (ObjectUtils.isEmpty(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        try {
            // 3.2判断token是否有效
            Claims claims = JwtUtils.parseJWT(token);
//            log.info("claims:{}",claims);
            // 3.3有效，放行
            chain.doFilter(request,response);
            return;
        } catch (Exception e) {
            // 3.4 如果无效，则返回401，拦截请求
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }

















    // @Override
    // public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    //     HttpServletRequest request = (HttpServletRequest) req;
    //     HttpServletResponse response = (HttpServletResponse) res;
    //     String uri = request.getRequestURI();
    //     if (uri.contains("/login")){
    //         chain.doFilter(request,response);
    //         return;
    //     }
    //     String token = request.getHeader("token");
    //     if (ObjectUtils.isEmpty(token)){
    //         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    //         return;
    //     }
    //     try {
    //         Claims claims = JwtUtils.parseJWT(token);
    //         chain.doFilter(request,response);
    //         return;
    //     }catch (Exception e){
    //         e.printStackTrace();
    //         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    //         return;
    //     }
    //
    //
    //
    // }

}
